package org.wx.io.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URI;
import java.nio.channels.FileChannel;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * @description: wx的httpServer Handler
 * @author: wangxun
 * @createDate: 2021/2/8
 * @version: 1.0
 */
@Slf4j
public class WxHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        if(msg instanceof HttpRequest){
            HttpRequest request = (HttpRequest) msg;
            String uriStr = request.uri();
            URI uri = new URI(uriStr);
            log.info("{}请求到达服务器,请求的资源是{}",ctx.channel().remoteAddress(),uri.getPath());

            ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer(4096);
            DefaultFullHttpResponse response = null;
            if("/favicon.ico".equals(uri.getPath())){
                // 网站的ico
                FileInputStream fileInputStream = new FileInputStream(new File("E:\\workspace\\my-java-se\\netty\\src\\main\\resources\\qian.png"));
                byte[] src = new byte[1024];

                int length =0;
                while ((length = fileInputStream.read(src))!=-1){
                    byte[] dist = new byte[1024];
                    System.arraycopy(src,0,dist,0,length);
                    byteBuf.writeBytes(dist);
                }
                fileInputStream.close();
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
                response.headers().set(HttpHeaderNames.CONTENT_TYPE,"image/x-icon");
                // 内容长度
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());
            }else {
                // 文本请求
                String s = new String("hello I am  wxHttpServer, O(∩_∩)O哈哈~");
                byteBuf.writeBytes(s.getBytes(UTF_8));
                // 封装一个response
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
                response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8");
                // 内容长度
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());
            }



            ctx.writeAndFlush(response);
        }


    }
}
